<script lang="ts">
	import {
		Table,
		TableBody,
		TableBodyCell,
		TableBodyRow,
		TableHead,
		TableHeadCell,
		ImagePlaceholder,
		Modal,
		Checkbox,
	} from 'flowbite-svelte'
	import { onDestroy, onMount } from 'svelte'
	import { slide } from 'svelte/transition'
	import type { IndicatorGroupKey, IpcResponse, Klt, ListParams } from './bindings'
	import type { IndicatorCombinationFilter } from './bindings/IndicatorCombinationFilter'
	import * as commands from '$lib/commands'
	import type { IndicatorComb } from './bindings/IndicatorComb'
	import {
		setIndicatorChartYaxises,
		unsetIndicatorChartYaxises,
		indicatorYaxisStore,
		klineRequestStore,
		klineResultStore,
	} from './FudaStore'
	import { derived, get } from 'svelte/store'
	import type { Unsubscriber } from 'svelte/motion'
	// indicator combination number
	export let comb: number = 1

	$: klineRequestState = $klineRequestStore

	let shouldReevaluateCheckboxes = false

	let indicatorCombinations: IndicatorComb[] | undefined = []
	// At the top level, define a derived store for checkbox states
	const derivedCheckboxStates = derived(indicatorYaxisStore, ($queue) => {
		return (
			indicatorCombinations?.map((combination) => ({
				...combination,
				checked: $queue.yaxisQueue.contains(combination.gks),
			})) || []
		)
	})
	let checkboxStates: { checked: boolean; gks: IndicatorGroupKey[]; cell_value: number }[] = []
	let subscription: Unsubscriber

	let openRow: number | null
	let details: IndicatorComb

	const toggleRow = (i: number) => {
		openRow = openRow === i ? null : i
	}

	function handleCheckboxChange(combination: { checked: any; gks: IndicatorGroupKey[] }) {
		if (!combination.checked) {
			// If the checkbox is unchecked, dequeue the keys
			unsetIndicatorChartYaxises(combination.gks)
		} else {
			// If checked, enqueue the keys
			setIndicatorChartYaxises(combination.gks)
		}

		// After modifications to the queue, indicate a reevaluation is needed
		shouldReevaluateCheckboxes = true
	}

	$: if (shouldReevaluateCheckboxes && indicatorCombinations) {
		console.log('Reevaluating checkboxes')
		// Iterate over combinations and update their checked status
		indicatorCombinations.forEach((combination) => {
			combination.checked = get(indicatorYaxisStore).yaxisQueue.contains(combination.gks)

			// console.log('combination.checked: ', combination.checked, combination.gks)
		})

		// Reset the flag after evaluation
		shouldReevaluateCheckboxes = false
	}

	onMount(async () => {
		console.log(
			`(Indicators.svelte) onMount with security_id=${klineRequestState.security_id}, klt=${klineRequestState.klt},size=${klineRequestState.page_size}, comb=${comb} `,
		)

		// Define the argument
		let args: ListParams<IndicatorCombinationFilter> = {
			page: 0,
			size: klineRequestState.page_size,
			filter: {
				security_id: klineRequestState.security_id,
				klt: klineRequestState.klt,
				comb_num: comb,
			},
		}

		const res: IpcResponse<IndicatorComb[]> = await commands.list_indicator_combinations(args)
		console.log('(Indicators.svelte) list_indicator_combinations.ipcResponse ', res)

		if (res.error) {
			// If the response status is not OK, throw an error
			throw new Error(`(Indicators.svelte) Server returned an error: ${res.error}`)
		}
		indicatorCombinations = res.result?.data
		shouldReevaluateCheckboxes = true

		subscription = derivedCheckboxStates.subscribe((data) => {
			checkboxStates = data
		})
	})

	onDestroy(() => {
		if (subscription) subscription()
	})
</script>

<Table hoverable={true}>
	<TableHead defaultRow={false}>
		<TableHeadCell class="w-1 px-2">#</TableHeadCell>
		<TableHeadCell class="text-nowrap whitespace-nowrap px-2">
			Indicators comb({comb})
		</TableHeadCell>
		<TableHeadCell class=" px-2">Value</TableHeadCell>
	</TableHead>
	<TableBody tableBodyClass="divide divide-solid divide-green-200 text-xs text-gray-500">
		{#if checkboxStates}
			{#each checkboxStates as item, i}
				<TableBodyRow
					class="hover:bg-blue-300 focus-within:bg-blue-500 bg-gray-200"
					on:click={() => toggleRow(i)}
				>
					<TableBodyCell tdClass="p-1 w-1">
						<Checkbox
							class="p-0"
							bind:checked={checkboxStates[i].checked}
							on:change={() => handleCheckboxChange(checkboxStates[i])}
						/>
					</TableBodyCell>
					<TableBodyCell tdClass="p-1">{item.gks}</TableBodyCell>
					<TableBodyCell tdClass="p-1">{item.cell_value.toFixed(2)}</TableBodyCell>
				</TableBodyRow>
				{#if openRow === i}
					<TableBodyRow on:dblclick={() => (details = item)}>
						<TableBodyCell colspan="4" class="p-0">
							<div class="px-2 py-3" transition:slide={{ duration: 300, axis: 'y' }}>
								<ImagePlaceholder />
							</div>
						</TableBodyCell>
					</TableBodyRow>
				{/if}
			{/each}
		{/if}
	</TableBody>
</Table>
